//
//  RBDataBaseTool.m
//  数据库操作
//
//  Created by RaoBo on 2018/7/6.
//  Copyright © 2018年 RaoBo. All rights reserved.
//

#import "RBDataBaseTool.h"
#import <FMDB.h>
#import "XJCommunityModel.h"

#define kCommunityModelDataBase @"communityModel.sqlite"

// 表名 cmtModel
//表的属性 cmtModel_id   name   address  community_id(请求参数必要✅)

static RBDataBaseTool *_dbCtl = nil;


@interface RBDataBaseTool()
{
    FMDatabase *_db;
}
@end

@implementation RBDataBaseTool
+ (instancetype)shareDataBase {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _dbCtl = [[RBDataBaseTool alloc] init];
        
        [_dbCtl initWithDataBase];
    });
    
    return _dbCtl;
}



- (void)initWithDataBase {
    //1.获取文件目录
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    //文件路径
    NSString *filePath = [documentPath stringByAppendingPathComponent:kCommunityModelDataBase];
    
    NSLog(@"数据库路径:%@",filePath);
    
    //实例化FMDatabase对象
    _db = [FMDatabase databaseWithPath:filePath];
    
    BOOL openResult = [_db open];
    
    if (openResult) { //数据库成功打开后 初始化下面语句
        NSString *sqlStr = @"CREATE TABLE IF NOT EXISTS 'cmtModel' ('cmtModel_id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'name' VARCHAR(255),'address' VARCHAR(255) ,'community_id' VARCHAR(255))";
        [_db executeUpdate:sqlStr];
    }
    
    
    //关闭数据库
    [_db close];
}


#pragma mark - 接口
- (void)addCommunityModel:(XJCommunityModel *)model {
    BOOL openResult = [_db open];
    
    if (!openResult) {
        return;
    }
    
    NSNumber *maxId = @(0);
    FMResultSet *res = [_db executeQuery:@"SELECT * FROM cmtModel"];
    while ([res next]) {
        NSString *nextCtyModel = [res stringForColumn:@"cmtModel_id"];
        
        if ([maxId integerValue] < [nextCtyModel integerValue]) {
            maxId = @([nextCtyModel integerValue]);
        }
    }
    
    maxId = @([maxId integerValue] +1);
    
    
//    表名 cmtModel
    
    //表的属性 cmtModel_id   name   address

    //执行插入语句
    BOOL updateResult = [_db executeUpdate:@"INSERT INTO cmtModel(cmtModel_id,name,address,community_id) VALUES(?,?,?,?)",maxId, model.name,model.address,model.community_id];
    
    if (updateResult) {
        NSLog(@"插入成功");
    }else {
        NSLog(@"插入失败");
    }
    
    [_db close];
}



- (void)deleteCommunityModel:(XJCommunityModel *)model {
    BOOL openRes = [_db open];
    
    if (!openRes) {
        return;
    }
    
    //删除
    BOOL deleteResult = [_db executeUpdate:@"DELETE FROM cmtModel WHERE cmtModel_id=?", model.ID];
    
    if (deleteResult) {
        NSLog(@"删除成功");
    }else {
        NSLog(@"删除失败");
    }
    
    [_db close];
}

- (NSMutableArray *)queryAllCommunityModel {
    
     BOOL openRes = [_db open];
    if (!openRes) return nil;
    
    // 准备容器
    NSMutableArray *tempArr = [NSMutableArray array];
    
    FMResultSet *res = [_db executeQuery:@"SELECT * FROM cmtModel"];
    while ([res next]) {
        
        XJCommunityModel *model = [XJCommunityModel new];
        
        model.ID = @([[res stringForColumn:@"cmtModel_id"] integerValue]);
        model.name = [res stringForColumn:@"name"];
        model.address = [res stringForColumn:@"address"];
        model.community_id = [res stringForColumn:@"community_id"];

        [tempArr addObject:model];
    }
    
    //关闭数据库
    [_db close];
    
    return tempArr;
}

- (void)deleteAllCommunityModel {
    
    
    BOOL isOpen = [_db open];
    if (!isOpen) {
        NSLog(@"打开数据库失败");
        return;
    }
    
    NSString *deleteSqlStr = [NSString stringWithFormat:@"DELETE from cmtModel"];
    
    BOOL isDelete = [_db executeUpdate:deleteSqlStr];
    if (isDelete) {
        NSLog(@"删除该人的所有车成功");
    }else{
        NSLog(@"删除该人的所有车失败");
    }
    
    // 关闭数据库
    [_db close];
}


@end










